package com.cincc.cinccimdemo.ui.conversation.detail;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.cincc.cinccimdemo.R;
import com.cincc.cinccimdemo.adapter.ConversationDetailMemberAdapter;
import com.cincc.cinccimdemo.common.AttrConstants;
import com.cincc.cinccimdemo.common.Constants;
import com.cincc.cinccimdemo.common.MyUtils;
import com.cincc.cinccimdemo.model.ConversationInfo;
import com.cincc.cinccimdemo.ui.IMBaseActivity;
import com.cincc.cinccimdemo.ui.conversation.member.AddMemberActivity;
import com.cincc.cinccimdemo.ui.conversation.member.RemoveMemberActivity;
import com.cincc.cinccimdemo.ui.conversation.sharefile.GroupShareFileActivity;
import com.cincc.cinccimdemo.ui.me.QRCodeActivity;
import com.cincc.cinccimdemo.widget.OptionItemView;
import com.cincc.im.callback.ImCallback;
import com.cincc.im.core.IMSipPhoneCtrl;
import com.cincc.im.core.SipCoreUtils;
import com.cincc.im.listener.ImRcvGroupNotifyListener;
import com.cincc.im.model.ImResponse;
import com.cincc.im.model.dbmodel.GroupInfo;
import com.cincc.im.model.dbmodel.GroupMemberInfo;
import com.cincc.im.model.enums.DisturbState;
import com.cincc.im.model.enums.GroupRoleType;
import com.cincc.im.model.notify.group.GroupNotify;
import com.cincc.im.model.notify.notifyenum.GroupNotifyType;
import com.google.android.material.switchmaterial.SwitchMaterial;
import com.lqr.imagepicker.ImagePicker;
import com.lqr.imagepicker.bean.ImageItem;

import java.util.ArrayList;
import java.util.List;

public class GroupDetailActivity extends IMBaseActivity implements CompoundButton.OnCheckedChangeListener, ImRcvGroupNotifyListener {
    private static final String TAG = "SingleDetailActivity";

    @Override
    protected int contentLayout() {
        return R.layout.activity_group_conversation_detail;
    }

    RecyclerView recyclerView;
    SwitchMaterial silentSwitchButton;
    SwitchMaterial stickTopSwitchButton;

    ProgressBar progressBar;
    NestedScrollView contentNestedScrollView;
    private static final int MEDIA_ALBUM_CODE = 1201;
    private static final int REQUEST_CODE_PICK_IMAGE = 1202;

    @Override
    protected void bindViews() {
        super.bindViews();
        recyclerView = findViewById(R.id.memberRecyclerView);
        silentSwitchButton = findViewById(R.id.silentSwitchButton);
        stickTopSwitchButton = findViewById(R.id.stickTopSwitchButton);
        progressBar = findViewById(R.id.progressBar);
        contentNestedScrollView = findViewById(R.id.contentNestedScrollView);
    }

    @Override
    protected void bindEvents() {
        super.bindEvents();
        SipCoreUtils.getInstance().addImRcvGroupNotifyListener(this);
        silentSwitchButton.setOnCheckedChangeListener(this);
        stickTopSwitchButton.setOnCheckedChangeListener(this);
        findViewById(R.id.groupNameOptionItemView).setOnClickListener(v -> groupNameOption());
        findViewById(R.id.groupPortraitOptionItemView).setOnClickListener(v -> groupPortraitOption());
        findViewById(R.id.groupQRCodeOptionItemView).setOnClickListener(v -> groupQRCodeOption());
        findViewById(R.id.groupShareFileOptionItemView).setOnClickListener(v -> groupShareFileOption());
        findViewById(R.id.groupNoticeLinearLayout).setOnClickListener(v -> groupNotice());
        findViewById(R.id.groupRemarkOptionItemView).setOnClickListener(v -> groupRemarkOption());
        findViewById(R.id.groupManageOptionItemView).setOnClickListener(v -> groupManageOption());

        findViewById(R.id.myGroupNickNameOptionItemView).setOnClickListener(v -> myGroupNickNameOption());
        findViewById(R.id.clearMessagesOptionItemView).setOnClickListener(v -> clearHistory());
        findViewById(R.id.quitButton).setOnClickListener(v -> quit());
        findViewById(R.id.showAllMemberButton).setOnClickListener(v -> showAllMember());
    }


    ConversationInfo conversationInfo;
    GroupInfo groupInfo;
    List<GroupMemberInfo> groupMemberList;
    ConversationDetailMemberAdapter memberAdapter;

    @Override
    protected void afterViews() {
        super.afterViews();
        conversationInfo = getIntent().getParcelableExtra("conversationInfo");
        groupInfo = IMSipPhoneCtrl.getInstance().getGroupInfo(conversationInfo.targetId);
        groupMemberList = IMSipPhoneCtrl.getInstance().getGroupMemberList(conversationInfo.targetId);
        memberAdapter = new ConversationDetailMemberAdapter(this, true, GroupRoleType.isMaster(groupInfo.roleInGroup));
        recyclerView.setAdapter(memberAdapter);
        memberAdapter.setList(groupMemberList);
        memberAdapter.setOnMemberClickListener(new ConversationDetailMemberAdapter.OnMemberClickListener() {
            @Override
            public void addMemberClick() {
                addMember();
            }

            @Override
            public void delMemberClick() {
                removeMember();
            }
        });
        progressBar.setVisibility(View.GONE);
        contentNestedScrollView.setVisibility(View.VISIBLE);

        refreshUI();

        IMSipPhoneCtrl.getInstance().getGroupInfo(conversationInfo.targetId, imResponse -> {
            if (imResponse.getCode() == 0) {
                runOnUiThread(this::refreshUI);
            }
        });
        IMSipPhoneCtrl.getInstance().getGroupMemberList(groupInfo.groupId, imResponse -> {
            if (imResponse.getCode() == 0) {
                runOnUiThread(this::refreshUI);
            }
        });
    }

    private void addMember() {
        String[] checkedUids = new String[groupMemberList.size()];
        for (int i = 0; i < groupMemberList.size(); i++) {
            checkedUids[i] = groupMemberList.get(i).memberId;
        }
        Intent i = new Intent(this, AddMemberActivity.class);
        i.putExtra(AttrConstants.MEMBER_IDS, checkedUids);
        i.putExtra(AttrConstants.GROUP_ID, groupInfo.groupId);
        startActivity(i);
    }

    private void removeMember() {
        Intent i = new Intent(this, RemoveMemberActivity.class);
        i.putExtra(AttrConstants.GROUP_ID, groupInfo.groupId);
        startActivity(i);
    }

    private void refreshUI() {
        groupInfo = IMSipPhoneCtrl.getInstance().getGroupInfo(conversationInfo.targetId);
        OptionItemView groupName = findViewById(R.id.groupNameOptionItemView);
        OptionItemView remark = findViewById(R.id.groupRemarkOptionItemView);
        TextView groupNotice = findViewById(R.id.groupNoticeTextView);
        groupName.setDesc(groupInfo.name);
        remark.setDesc(groupInfo.remark);
        groupNotice.setText(groupInfo.notice);
        groupNotice.setVisibility(TextUtils.isEmpty(groupInfo.notice) ? View.GONE : View.VISIBLE);
        OptionItemView groupPortraitOptionItemView = findViewById(R.id.groupPortraitOptionItemView);

        if (!TextUtils.isEmpty(groupInfo.protraitUrl)) {
            Glide.with(GroupDetailActivity.this).load(groupInfo.protraitUrl).placeholder(R.mipmap.avatar_def)
                    .transforms(new CenterCrop(), new RoundedCorners(15))
                    .into(groupPortraitOptionItemView.getEndImageView());
        }
        silentSwitchButton.setChecked(groupInfo.noDisturb);
        stickTopSwitchButton.setChecked(groupInfo.isTop);
        TextView quit = findViewById(R.id.quitButton);
        quit.setText(GroupRoleType.isMaster(groupInfo.roleInGroup) ? "解散并删除" : "退出并删除");
    }


    private void setConversationTop(boolean isCheck) {
        IMSipPhoneCtrl.getInstance().setTop(conversationInfo.imSendType, conversationInfo.targetId, isCheck);
        MyUtils.fireConversationListRefreshEvent();
    }

    private void setConversationNoDisturb(boolean isCheck) {
        IMSipPhoneCtrl.getInstance().disturb(conversationInfo.imSendType, isCheck ? DisturbState.ON : DisturbState.OFF, conversationInfo.targetId, new ImCallback() {
            @Override
            public void callback(ImResponse imResponse) {
                Log.e(TAG, "setConversationNoDisturb callback: " + imResponse.getCode());
                runOnUiThread(MyUtils::fireConversationListRefreshEvent);
            }
        });
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        int id = buttonView.getId();
        if (id == R.id.stickTopSwitchButton) {
            setConversationTop(isChecked);
        } else if (id == R.id.silentSwitchButton) {
            setConversationNoDisturb(isChecked);
        }
    }

    private void groupNameOption() {
        if (GroupRoleType.isMaster(groupInfo.roleInGroup)) {
            Intent intent = new Intent(this, EditGroupInfoActivity.class);
            intent.putExtra("type", 0);
            intent.putExtra("groupId", conversationInfo.targetId);
            intent.putExtra("data", groupInfo.name);
            startActivity(intent);
        }
    }

    private void groupPortraitOption() {
        if (GroupRoleType.isMaster(groupInfo.roleInGroup)) {
            String[] permissions;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                permissions = new String[]{
                        Manifest.permission.READ_MEDIA_IMAGES,
                };
            } else {
                permissions = new String[]{
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                };
            }
            for (String permission : permissions) {
                if (checkCallingOrSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
                    requestPermissions(permissions, MEDIA_ALBUM_CODE);
                    return;
                }
            }
            ImagePicker.picker().pick(this, REQUEST_CODE_PICK_IMAGE);
        }
    }

    private void groupQRCodeOption() {
        QRCodeActivity.startQrcode(this, conversationInfo.imSendType.value(), conversationInfo.targetId);
    }

    private void groupShareFileOption() {
        GroupShareFileActivity.startShareFilePage(this, conversationInfo.targetId);
    }

    private void groupNotice() {
        if (GroupRoleType.isMaster(groupInfo.roleInGroup)) {
            Intent intent = new Intent(this, EditGroupInfoActivity.class);
            intent.putExtra("type", 1);
            intent.putExtra("groupId", conversationInfo.targetId);
            intent.putExtra("data", groupInfo.notice);
            startActivity(intent);
        }
    }

    private void groupRemarkOption() {
        Intent intent = new Intent(this, EditGroupInfoActivity.class);
        intent.putExtra("type", 2);
        intent.putExtra("groupId", conversationInfo.targetId);
        intent.putExtra("data", groupInfo.remark);
        startActivity(intent);
    }

    private void groupManageOption() {

    }

    private void myGroupNickNameOption() {
        Intent intent = new Intent(this, EditGroupInfoActivity.class);
        intent.putExtra("type", 3);
        intent.putExtra("groupId", conversationInfo.targetId);
        intent.putExtra("data", groupInfo.nickNameInGroup);
        startActivity(intent);
    }

    private void quit() {
        String title = GroupRoleType.isMaster(groupInfo.roleInGroup) ? "解散群组" : "退出群组";
        String content = GroupRoleType.isMaster(groupInfo.roleInGroup) ? "确定要解散群组吗？" : "确定要退出群组吗？";

        new AlertDialog.Builder(this)
                .setTitle(title)
                .setMessage(content)
                .setPositiveButton("确定", (dialog, which) -> {
                    if (GroupRoleType.isMaster(groupInfo.roleInGroup)) {
                        IMSipPhoneCtrl.getInstance().deleteGroup(conversationInfo.targetId, new ImCallback() {
                            @Override
                            public void callback(ImResponse imResponse) {
                                Log.e(TAG, "deleteGroup callback: " + imResponse.getCode() + ",msg = " + imResponse.getMsg());
                                if (imResponse.getCode() == 0) {
                                    runOnUiThread(() -> {
                                        Intent intent = new Intent(GroupDetailActivity.this.getPackageName() + ".main");
                                        startActivity(intent);
                                    });
                                } else {
                                    Toast.makeText(GroupDetailActivity.this, "解散群组失败", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    } else {
                        List<String> list = new ArrayList<>();
                        list.add(Constants.userInfo.userId);
                        IMSipPhoneCtrl.getInstance().deleteGroupMember(conversationInfo.targetId, list, new ImCallback() {
                            @Override
                            public void callback(ImResponse imResponse) {
                                Log.e(TAG, "deleteGroupMember callback: " + imResponse.getCode() + ",msg = " + imResponse.getMsg());
                                if (imResponse.getCode() == 0) {
                                    runOnUiThread(() -> {
                                        Intent intent = new Intent(GroupDetailActivity.this.getPackageName() + ".main");
                                        startActivity(intent);
                                    });
                                } else {
                                    Toast.makeText(GroupDetailActivity.this, "退出群组失败", Toast.LENGTH_SHORT).show();
                                }
                            }
                        });
                    }
                })
                .setNegativeButton("取消", (dialog, which) -> {
                    // do nothing
                })
                .show();

    }

    private void showAllMember() {

    }

    private void clearHistory() {
        IMSipPhoneCtrl.getInstance().clearHistoryMsg(conversationInfo.imSendType, conversationInfo.targetId, new ImCallback() {
            @Override
            public void callback(ImResponse imResponse) {
                Log.e(TAG, "clearHistory callback: " + imResponse.getCode());
                String result = imResponse.getCode() == 0 ? "清空聊天记录成功" : imResponse.getMsg();
                runOnUiThread(() -> {
                    Toast.makeText(GroupDetailActivity.this, result, Toast.LENGTH_SHORT).show();
                    MyUtils.fireConversationRefreshEvent();
                    MyUtils.fireConversationListRefreshEvent();
                });
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SipCoreUtils.getInstance().addImRcvGroupNotifyListener(this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MEDIA_ALBUM_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                ImagePicker.picker().pick(this, REQUEST_CODE_PICK_IMAGE);
            } else {
                Toast.makeText(this, "请打卡相册权限", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_PICK_IMAGE && resultCode == Activity.RESULT_OK) {
            ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
            if (images == null || images.isEmpty()) {
                Toast.makeText(this, "更新群头像失败: 选取文件失败 ", Toast.LENGTH_SHORT).show();
                return;
            }
            String imagePath = images.get(0).path;
            Log.e(TAG, "onActivityResult:imagePath = " + imagePath);
            IMSipPhoneCtrl.getInstance().updateGroupAvatar(conversationInfo.targetId, imagePath, imResponse -> {
                String result = imResponse.getCode() == 0 ? "修改成功" : imResponse.getMsg();
                IMSipPhoneCtrl.getInstance().getGroupInfo(conversationInfo.targetId, imResponse1 -> {
                    if (imResponse1.getCode() == 0) {
                        runOnUiThread(this::refreshUI);
                    }
                });
                runOnUiThread(() -> Toast.makeText(GroupDetailActivity.this, result, Toast.LENGTH_SHORT).show());
            });
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public void onReceiveGroupNotify(GroupNotify message) {
        if (message.notifyType == GroupNotifyType.GROUP_MEMBER_ADD || message.notifyType == GroupNotifyType.GROUP_MEMBER_DEL) {
            runOnUiThread(() -> {
                groupMemberList = IMSipPhoneCtrl.getInstance().getGroupMemberList(conversationInfo.targetId);
                memberAdapter.setList(groupMemberList);
            });
        }
        if (message.notifyType == GroupNotifyType.GROUP_NOTICE_HAS_CHANGE || message.notifyType == GroupNotifyType.GROUP_INFO_HAS_CHANGE) {
            runOnUiThread(this::refreshUI);
        }
    }
}
